package ltd.hxya.novel.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import ltd.hxya.novel.common.bean.Query;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.bean.UserBean;
import ltd.hxya.novel.common.utils.JwtUtils;
import ltd.hxya.novel.user.entity.User;
import ltd.hxya.novel.user.entity.UserBookshelf;
import ltd.hxya.novel.user.entity.dto.*;
import ltd.hxya.novel.user.interceptor.UserLoginInterceptor;
import ltd.hxya.novel.user.service.IUserBookshelfService;
import ltd.hxya.novel.user.service.IUserService;
import ltd.hxya.novel.user.vo.UserInfoVo;
import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hxya
 * @since 2022-09-13
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserBookshelfService userBookshelfService;


    /**
     * 查询当前登录的用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVo> userInfo(){

        UserInfoVo userInfoVo = userService.userInfo();

        return Result.success(userInfoVo);
    }

    /**
     * 用户注册接口
     */
    @PostMapping("register")
    public Result<UserRegisterRespDto> register(@Valid @RequestBody UserRegisterReqDto dto) {
        return userService.register(dto);
    }

    /**
     * 获得验证码
     */
    @GetMapping("/verifyCode")
    public Result<Map<String, String>> verifyCode(HttpServletRequest request) throws IOException {
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Map<String, String> img = userService.verifyCode();
        return Result.success(img);
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        UserBean userBean = UserLoginInterceptor.threadLocal.get();
        String id = userBean.getId();
        User user = new User();
        BeanUtils.copyProperties(userInfoVo,user);
        user.setId(id);
        userService.updateById(user);
        return Result.success();
    }

    // 图片验证码的获取处理  img_verify_code
    /**
     * 获取图片验证码接口
     * 把图片存在了redis中，并且设置了时间
     * @return
     * @throws IOException
     */
    @Operation(summary = "获取图片验证码接口")
    @GetMapping("/img_verify_code")
    public Result<ImgVerifyCodeRespDto> getImgVerifyCode() throws IOException {
        return userService.getImgVerifyCode();
    }


    /**
     * 用户登录接口
     */
    @Operation(summary = "用户登录接口")
    @PostMapping("/login")
    public Result<UserLoginRespDto> login(@Valid @RequestBody UserLoginReqDto dto) {
        return userService.login(dto);
    }

    /**
     * 用户信息查询接口
     */
    @Operation(summary = "用户信息查询接口")
    @GetMapping
    public Result<UserInfoRespDto> getUserInfo(HttpServletRequest request) {
        // 获取token
        String token = request.getHeader("Authorization");
        String json = JwtUtils.checkToken(token);
        User user = JSON.parseObject(json, new TypeReference<User>() {});
        return userService.getUserInfo(user.getId());
    }


    /**
     * 用户信息修改接口
     */
    @Operation(summary = "用户信息修改接口")
    @PutMapping
    public Result<Void> updateUserInfo(@Valid @RequestBody UserInfoUptReqDto dto,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String json = JwtUtils.checkToken(token);
        User user = JSON.parseObject(json, new TypeReference<User>() {});
        dto.setUserId(user.getId());
        return userService.updateUserInfo(dto);
    }

    /**
     * 给上一章，下一章来进行跨服务调用的处理的
     * @param bookId
     * @param contentId
     */
    @PostMapping("/userShelf")
    public void saveUserBookShelf(String bookId,String contentId,String token){
        String userId = getUserId(token);
        if (!StringUtils.isEmpty(userId)){
            QueryWrapper<UserBookshelf> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("book_id", bookId);
            long count = userBookshelfService.count(queryWrapper);

            UserBookshelf userBookshelf = new UserBookshelf();
            userBookshelf.setUserId(userId);
            userBookshelf.setBookId(bookId);
            userBookshelf.setPreContentId(contentId);
            userBookshelf.setUpdateTime(LocalDateTime.now());

            // count = 1,表示有数据
            if (count ==1){
                String id = userBookshelfService.getOne(queryWrapper).getId();
                userBookshelf.setId(id);
                userBookshelfService.updateById(userBookshelf);
            }else {
                userBookshelfService.save(userBookshelf);
            }
        };
    }

    @PostMapping("/getProContentId")
    public String getProContentId(String bookId,String token){
        String userId = getUserId(token);
        // 没有token，就是没有登录，那么就直接返回空
        QueryWrapper<UserBookshelf> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
                .eq("book_id",bookId);
        long count = userBookshelfService.count(queryWrapper);
        // 查到了就返回对应的章节id，没查到的话然后""空
        if (count==1){
            String preContentId = userBookshelfService.getOne(queryWrapper).getPreContentId();
            return preContentId;
        }else {
            return "";
        }
    }


    public String getUserId(String token){
        String json = JwtUtils.checkToken(token);
        User user = JSON.parseObject(json, new TypeReference<User>() {});
        return user.getId();
    }

    /**
     *获取到用户id的处理,
     * @return
     */
    @PostMapping("/getUserId")
    public String getUserIds(String token){
        String json = JwtUtils.checkToken(token);
        User user = JSON.parseObject(json, new TypeReference<User>() {});
        return user.getId();
    }






}
